//修改密码弹窗

import React, { useState, useMemo, useEffect } from 'react';
import { getCode } from '@/services/user';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { Form, Input, Button, Row, Col, message, Popover } from 'antd';
import { changePassword } from '../../service'
import { passWord } from '@/utils/rule';
import { getDifferUserDetails } from '@/utils/authority';

export default ({ PasswordModalSwitch, PasswordModalOk, PasswordModalNo }) => {

    const [second, setSecond] = useState(0)
    const [spinning, setSpinning] = useState(false)

    const personageMessage = useMemo(()=>{
        return getDifferUserDetails();
      }, [])

    useEffect(() => {
        // dispatch({ type: 'accountSafety/getInitPage' });
        if (PasswordModalSwitch) {
            form.resetFields();
        }
    }, [PasswordModalSwitch])

    const layout = {
        labelCol: {
            span: 5,
        },
        wrapperCol: {
            span: 16,
        },
    };

    const [form] = Form.useForm();

    //修改密码校验事件
    const PasswordModalVerify = async () => {
        form.validateFields().then(async () => {
            const arr = form.getFieldsValue()
            arr.mobile = personageMessage.mobile
            arr.tenantId = '000000'
            arr.type = 1
            if (arr.newPwd !== arr.repeatPwd) {
                message.error('两次输入密码不一致')
                return;
            }
            setSpinning(true)
            const res = await changePassword(arr)
            if (res.code == 200) {
                message.success('修改密码成功')
                PasswordModalOk()
                form.resetFields()
            }
            let timer = setTimeout(() => {
                setSpinning(false);
                clearTimeout(timer);
                timer = null;
            }, 300)
        }).catch(() => {

        })
    }

    //点击弹框取消事件
    const PasswordModalCancel = async () => {
        PasswordModalNo()
        form.resetFields()
    }

    //获取验证码
    const code = async (phone) => {
        const res = await getCode({
            mobile: phone,
            type: 3
        })
        if (res.success) {
            message.success('验证码发送成功！');
        }
    }

    //获取验证码点击校验倒数事件
    const verification = async () => {
        let num = 59
        setSecond(59)
        let seconds = setInterval(() => {
            num = num - 1
            setSecond(num)
            if (num === 0) {
                clearInterval(seconds);
                setSecond(0);
            }
        }, 1000)
        code(personageMessage.mobile)
    }

    return (
        <CommonModal
            title="修改密码"
            visible={PasswordModalSwitch}
            onCancel={PasswordModalCancel}
            width={480}
            footer={[
                <Button key={1} onClick={PasswordModalCancel} loading={spinning}>取消</Button>,
                <Button key={2} type="primary" onClick={PasswordModalVerify} loading={spinning}>确定</Button>
            ]}
        >
            <div className="form_box">
                <Form
                    {...layout}
                    name="password"
                    form={form}
                    initialValues={{
                        mobile: personageMessage.mobile,
                    }}
                >
                    <Form.Item
                        label="手机号"
                        name="mobile"
                    >
                        <Input style={{ width: 325 }} disabled />
                    </Form.Item>

                    <Form.Item
                        label="手机验证"
                        name="smsCode"
                        rules={[
                            {
                                required: true,
                                message: '请输入手机验证码!',
                            },
                        ]}>
                        <Row gutter={8}>
                            <Col span={15}>
                                <Input />
                            </Col>
                            <Col span={9}>
                                <Button style={{ width: '140px' }} disabled={second} onClick={verification}>{second ? `${second}s` : '获取验证码'}</Button>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Popover content={
                        <div style={{ width: '240px' }}>
                            <p style={{ marginBottom: '12px' }}>1、密码至少为8位，且必须包含大小写字母、数字和特殊字符三种</p>
                            <p>2、特殊字符支持的有：{`!，@，#，$，%，^，&`}</p>
                        </div>
                    } trigger={['click']} placement="right">
                        <Form.Item
                            label="新密码"
                            name="newPwd"
                            rules={[
                                { required: true, message: '请输入密码' },
                                { pattern: /^[^\u4e00-\u9fa5]{1,}$/g, message: '不支持中文' },
                                { pattern: /^[^\s]*$/, message: '不能包含空格' },
                                passWord,
                            ]}
                        >
                            <Input.Password style={{ width: 325 }} autoComplete="new-password" />
                        </Form.Item>
                    </Popover>
                    <Form.Item
                        label="重复密码"
                        name="repeatPwd"
                        rules={[
                            {
                                required: true,
                                message: '请再次输入密码!',
                            },
                            ({ getFieldValue }) => ({
                                validator(rule, value) {
                                    if (!value || getFieldValue('newPwd') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject('两次输入密码不一致');
                                },
                            }),
                        ]}
                    >
                        <Input.Password style={{ width: 325 }} autoComplete="new-password" />
                    </Form.Item>
                </Form>
            </div >
            <CommonLoading loading={spinning} />
        </CommonModal >
    )
}